package com.example.spring2013android;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class ObjectsReader
{
	private static final String TAG = "ObjectsReader";
	List<Contact> retrievedresult = null;
	public  List<Contact> readContacts(String jsonFileUrl)
	{
		List<Contact> listofcontacts = new ArrayList<Contact>();
		
		InputStream source = retrieveStream(jsonFileUrl);
		
		  Reader reader = new InputStreamReader(source);

	        Gson gson = new Gson();

	        Type listType = new TypeToken<ContactsResponse>()
	        {
	        }.getType();

	        listofcontacts = gson.fromJson(reader, listType);
		
		return listofcontacts;
		
	}
	
    public List<Contact> readPersons(String jsonFileUrl)
    {

        InputStream source = retrieveStream(jsonFileUrl);

        Reader reader = new InputStreamReader(source);

        Gson gson = new Gson();

        Type listType = new TypeToken<List<Contact>>()
        {
        }.getType();

        retrievedresult = gson.fromJson(reader, listType);

        if (retrievedresult != null)
        {

            for (Contact res : retrievedresult)
            {
                Log.d(TAG, "------------------" + res.getName());
                Log.d(TAG, "-----------------" + res.getAge());

            }

        }

        return retrievedresult;
    }
    private  InputStream retrieveStream(String url)
    {

        DefaultHttpClient client = new DefaultHttpClient();

        HttpGet getRequest = new HttpGet(url);

        try
        {

            HttpResponse getResponse = client.execute(getRequest);
            final int statusCode = getResponse.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK)
            {
                Log.w(TAG, "Error " + statusCode + " for URL " + url);
                return null;
            }

            HttpEntity getResponseEntity = getResponse.getEntity();
            return getResponseEntity.getContent();

        } catch (IOException e)
        {
            getRequest.abort();
            Log.w(TAG, "Error for URL " + url, e);
        }

        return null;

    }

}
